const basicAnth = require('basic-auth')
const jwt = require('jsonwebtoken')
const security = require('./tokentime.js').security
const result = require('../config/handle.js')

class Auth{
	 constructor(){}
	 // 取值函数 
	 get m(){
		 return async(ctx,next)=>{
			 const token = basicAnth(ctx.req)
			 console.log(token)
			if(!token || !token.name){
				throw new result({errcode:'401',msg:'没有访问权限'},401)
				}
				try{
					// 验证token合法性
					var authcode = jwt.verify(token.name,security.secretKey)
					console.log(authcode)
				}catch(e){
					//TODO handle the exception
					if(error.name == 'TokenExpiredError'){
						throw new result({errcode:'401',msg:'账号过期，请重新登录'},401)
					}
					throw new result({errcode:'401',msg:'没有访问权限'},401)
				}
				ctx.auth={
					uid:authcode.uid
				}
				await next()
		 }
		 
	 }
}
module.exports={ Auth }